<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\model\AppleDebtBacked;
use app\common\model\AppleRepayPlan;
use app\common\model\NokiaMember;
use app\common\model\NokiaMemberContact;
use app\common\model\OppoOrder;
use app\common\model\OppoOrderAddr;
use app\common\model\OppoOrderDelivery;
use app\common\model\OppoOrderMember;
use app\common\model\SonyOrderRepay;
use app\common\model\SonyProtocolSignTask;
use app\common\model\SysMerchantWithdraw;
use app\common\service\DeptBackedService;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\facade\Db;
use think\facade\Log;

/**
 * 订单列表
 */
class Order extends Controller{

    //订单状态 2:待付款(审核通过) 3:待发货(已付款) 4:待收货 5:待归还 6:成功 7:关闭，交易订单从待发货开始，至成功或关闭结束
    public $status_arr = [2 => '代付款', 3 => '待发货', 4 => '待收货',5 => '待归还', 6 => '已完成', 7 => '已关闭'];

    public $plan_status_arr = ['待归还', '已结清', '已逾期', '已作废'];

    /**
     * 订单列表
     * @auth true
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        $this->title = '订单列表';
        $this->status = $this->get['status'] ?? 0;
        $query = OppoOrder::mQuery();
        $user = $this->app->session->get('user');
        if($user['id'] != 10000) $query->where('merchant_id', '=', $user['id']);
        if($this->request->get('status'))$query->equal('status');
        $query->equal('mobile');
        $query->like('goods_name,order_id,shop_name');
        $query->where(['del_flag' => 0]);
        $name = $this->request->get('nickname');
        if($name){
            $userId = NokiaMember::where('real_name', $name)->value('member_id');
            $query->where('member_id', '=', $userId);
        }
        $gmt_created = $this->request->get('gmt_created');
        if($gmt_created){
            $dateArr = explode(' - ', $gmt_created);
            $query->whereBetween('gmt_created', $dateArr);
        }
        $query->order('gmt_created desc')->page();
    }

    public function _index_page_filter(array &$data){
        foreach ($data as &$vo){
            $vo['name'] = NokiaMember::mk()->where(['member_id' => $vo['member_id']])->value('real_name');
            $vo['status_str'] = $this->status_arr[$vo['status']];
        }
    }

    /**
     * 账单列表
     * @auth true
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function plan()
    {
        $data = $this->_vali(['order_id.require' => '订单号不能为空！']);

        //订单信息
        $order = OppoOrder::mk()->where(['order_id' => $data['order_id']])->find();

        $lst = AppleRepayPlan::mk()->where(['order_id' => $data['order_id']])->order('id asc')->select()->toarray();

        $this->order_id = $data['order_id'];
        $deptArr = DeptBackedService::getPlanDept($data['order_id']);

        foreach ($lst as &$vo){
            $vo['status_str'] = $this->plan_status_arr[$vo['status']];
            $pay = isset($deptArr['pay'][$vo['plan_index']]) ? $deptArr['pay'][$vo['plan_index']] : 0;
            $jm = isset($deptArr['jianmian'][$vo['plan_index']]) ? $deptArr['jianmian'][$vo['plan_index']] : 0;
            $vo['pay'] = $pay;
            //$vo['shengyu'] = bcsub($vo['plan_total_amount'], (string)$pay, 2);
            $vo['shengyu'] = bcsub(bcsub($vo['plan_total_amount'], (string)$pay, 2), (string)$jm, 2);
            $vo['other'] = isset($deptArr['other'][$vo['plan_index']]) ? $deptArr['other'][$vo['plan_index']] : [];
            if($order['overdue_fine'] > 0){
                $vo['other'][] = '违约金：' . $vo['overdue_fine'];
            }
            if($vo['plan_index'] == 12){
                if($order['buy_sts'] !== 1){
                    $vo['shengyu'] = $vo['shengyu'] + $order['buy_amount'];
                    $vo['other'][] = '买断尾款：' . $order['buy_amount'];
                }
            }
        }
        $this->lst = $lst;
        $this->order = $order;
        $user = $this->app->session->get('user');
        $this->user_id = $user['id'];

        $this->fetch('plan');
    }

    /**
     * 创建还款单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function repayment()
    {
        if ($this->request->isGet()) {
            $plan_id = input('plan_id');
            $plan = AppleRepayPlan::mk()->where(['plan_id' => $plan_id])->find();
            $this->plan = $plan;
            $this->fetch('repayment');
        }else{
            $params = $this->_vali([
                'id.default' => 0,
                'bill_type.require' => '账单类型不能为空',
                'repay_type.require' => '还款类型不能为空',
                'pay_method.require' => '支付方式不能为空',
                'deduction_amount.default' => '',
                'amount.require' => '还款金额不能为空',
                'pay_time.require' => '请选择还款时间',
                'repay_voucher.default' => '',
                'repay_remark.default' => ''
            ]);
            $plan = AppleRepayPlan::mk()->where(['id' => $params['id']])->find();
            //用户信息
            $userInfo = OppoOrderMember::mk()->where(['order_id' => $plan['order_id'], 'member_id' => $plan['member_id']])->find();

            Db::startTrans();
            try {
                //付款单
                $log = [
                    'repay_id' => CodeExtend::uniqidDate(18, 'RE'),
                    'bill_id' => '',
                    'plan_id' => $plan['plan_id'],
                    'plan_index' => $plan['plan_index'],
                    'order_id' => $plan['order_id'],
                    'member_id' => $plan['member_id'],
                    'biz_type' => 1,
                    'repay_type' => $params['repay_type'],
                    'pay_method' => $params['pay_method'],
                    'payable_amount' => $plan['plan_amount'],
                    'pay_amount' => $params['amount'],
                    'remaining_amount' => $plan['plan_amount'],
                    'rent_amount' => $plan['plan_amount'],
                    'fine' => $plan['overdue_fine'],
                    'deduction_amount' => $params['deduction_amount'],
                    'repay_platform' => 0,
                    'repay_name' => '',
                    'repay_amount' => '',
                    'repay_voucher' => ["" . $params['repay_voucher']],
                    'repay_remark' => $params['repay_remark'],
                    'suggest' => 1,
                    'status' => 1,
                    'repay_time' => $params['pay_time'],
                    'creater' => '平台',
                    'tenant_id' => 10000,
                    'member_name' => $userInfo['real_name'],
                    'mobile' => $userInfo['mobile'],
                    'merchant_id' => $plan['merchant_id'],
                    'shop_name' => $plan['shop_name'],
                ];
                SonyOrderRepay::mk()->insert($log);

                $status = 0;
                $remaining_amount = 0;
                //判断是否全部还清
                $amount = $params['amount'];
                $rent = $plan['plan_total_amount'];
                $jm = $params['deduction_amount'];

                //还款记录
                //租金
                $backed = [
                    'backed_id' => CodeExtend::uniqidDate(18, 'BA'),
                    'debt_id' => '',
                    'debt_plan_id' => '',
                    'bill_id' => '',
                    'plan_index' => $plan['plan_index'],
                    'order_id' => $plan['order_id'],
                    'pay_id' => CodeExtend::uniqidDate(18, 'PA'),
                    'biz_type' => 1,
                    'member_id' => $plan['member_id'],
                    'backed_time' => $params['pay_time'],
                    'payable_amount' => $plan['plan_amount'],
                    'credit_amount' => $params['deduction_amount'],
                    'discount_amount' => 0,
                    'backed_type' => $params['repay_type'] == 1 ? 0 : 2,
                    'memo' => $params['repay_remark'],
                    'tenant_id' => 10000,
                    'merchant_id' => $plan['merchant_id'],
                    'shop_name' => $plan['shop_name'],
                ];
                if($params['bill_type'] == 1){
                    $bill_type = 1;
                    //已还款金额21
                    $finishPay = AppleDebtBacked::mk()->where(['order_id' => $plan['order_id'], 'plan_index' => $plan['plan_index'], 'status' => 1])->sum('payment_amount');
                    //还款金额 + 减免
                    $totalAmount = $finishPay + $amount + $jm;
                    if($totalAmount < $rent){
                        //部分还款
                        $payment_amount = $totalAmount;
                        $remaining_amount = $rent - $totalAmount;
                    }else{
                        //结清
                        $status = 1;
                        $payment_amount = $amount;
                    }

                }else{
                    //买断记录
                    $bill_type = 5;
                    $remaining_amount = 0;
                    $payment_amount = $amount;
                }
                $backed['bill_type'] = $bill_type;
                $backed['payment_amount'] = $amount;
                $backed['remaining_amount'] = $remaining_amount;
                $backed['status'] = 1;
                AppleDebtBacked::mk()->insert($backed);

                if($status == 1){
                    $plan->status = 1;
                    $plan->settle_time = date('Y-m-d H:i:s');
                    $plan->save();
                }

                if($plan['plan_index'] == 12 && $params['bill_type'] == 2){
                    $order = OppoOrder::mk()->where(['order_id' => $plan['order_id']])->find();
                    $order->buy_sts = 1;
                    $order->status = 6;
                    $order->save();
                }

                //记录商家收入
                $mWithdraw = SysMerchantWithdraw::where('merchant_id', '=', $plan['merchant_id'])->find();
                $mWithdraw->income_amount = bcadd($mWithdraw->income_amount, $amount, 2);
                $mWithdraw->withdrawal_amount = bcadd($mWithdraw->withdrawal_amount, $amount,2);
                $mWithdraw->save();
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('失败');
            }
        }
        $this->success('操作成功，请重新打开账单');
    }

    public function contact()
    {
        $data = $this->_vali(['member_id.require' => '订单号不能为空！']);

        //订单信息
        $this->lst = NokiaMemberContact::mk()->where(['member_id' => $data['member_id']])->select();
        $this->fetch('contact');
    }

    /**
     * 基础信息
     * @auth true
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function basic(){
        $data = $this->_vali(['order_id.require' => '订单号不能为空！']);

        $this->order = OppoOrder::mk()->where(['order_id' => $data['order_id']])->find();
        $this->order['status_str'] = $this->status_arr[$this->order['status']];
        $this->orderMember = OppoOrderMember::mk()->where(['order_id' => $data['order_id']])->find();
        $this->orderDelivery = OppoOrderdelivery::mk()->where(['order_id' => $data['order_id']])->find();
        $this->orderAddr = OppoOrderAddr::mk()->where(['order_id' => $data['order_id']])->find();
        $seal_success_url = SonyProtocolSignTask::mk()->where(['order_id' => $data['order_id'], 'template_type' => 100008])->value('seal_success_url');
        $this->order->sign_url = 'http://pdf.zujishuo.zlshuyun.com/' . $seal_success_url;
        $this->fetch('basic');
    }
}